package com.app.community.controller;

import com.app.community.dto.PosterDTO;
import com.app.community.dto.QuestionDTO;
import com.app.community.exception.ErrorCodeEnum;
import com.app.community.service.AvatarService;
import com.app.community.service.CommentService;
import com.app.community.service.IndexService;
import com.app.community.service.NotificationService;
import com.wordnik.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 2020/10/10 20:08
 **/
@Slf4j
@Controller
public class IndexController {

    @Autowired
    IndexService indexService;

    @Autowired
    CommentService commentService;

    @Autowired
    AvatarService avatarService;

    @Autowired
    HttpSession httpSession;

    @Autowired
    NotificationService notificationService;

    @ApiOperation("默认打开在第一面")
    @GetMapping(path = "/")
    public String index() {
        return "forward:index";
    }

    @GetMapping(path = "index/{id}")
    public String retrunIndex(@PathVariable("id")int id){
        return "forward:/" + id;
    }

    @ApiOperation("请求访问其他页面")
    @GetMapping(path = "/{id}")
    public String index(Model model, @PathVariable("id")Integer id){
        List<QuestionDTO> questions = indexService.selectQuestionDTO(id);

        getPageInfo(model,questions);

        // 当前页号传递给前端
        model.addAttribute("currentpage",id);
        model.addAttribute("pageinfo","index");
        return "common/index";
    }


    @GetMapping(path = "index")
    public String returnIndex(Model model) {
        List<QuestionDTO> questions = indexService.selectQuestionDTO(1);

        getPageInfo(model,questions);

        // 当前页号传递给前端
        model.addAttribute("currentpage",1);
        model.addAttribute("pageinfo","index");

        return "common/index";
    }


    @ApiOperation("根据title查询问题")
    @GetMapping("search")
    public String searchQuestion(@RequestParam(value = "search",required = false)String search, Model model){
//        如果用户输入为空则返回第一页的内容
        if (search == null || search.isEmpty()){
            model.addAttribute("search", ErrorCodeEnum.GETNOTHING.getDescription());
            List<QuestionDTO> questions = indexService.selectQuestionDTO(1);

            getPageInfo(model,questions);
            // 当前页号传递给前端
            model.addAttribute("currentpage",1);
            return "common/index";
        } else{
            // 用户搜索的内容仍然保持
            model.addAttribute("search",search);
            // 默认第一页
            List<QuestionDTO> questions = indexService.searchQuestionDTO(search,1);
            getPageInfo(model,questions);
            // 当前页号传递给前端
            model.addAttribute("currentpage",1);
            model.addAttribute("pageinfo","search");
        }

        return "common/index";
    }

    @GetMapping("search/{id}")
    public String searchQuestion(@RequestParam(value = "search",required = true)String search, Model model,@PathVariable("id")Integer id){
        // 用户搜索的内容仍然保持
        model.addAttribute("search",search);
        List<QuestionDTO> questions = indexService.searchQuestionDTO(search,id);
        getPageInfo(model,questions);

        // 当前页号传递给前端
        model.addAttribute("currentpage",id);
        model.addAttribute("pageinfo","search");

        return "common/index";
    }


    /**
     * 获取页数
     * @return 页数数组
     */
    private int[] getPages(int count){
        // 计算页数
        int page;

        if (count % 10 == 0){
            page = count / 10;
        }else {
            page = (count / 10) + 1;
        }
        // 创建一个列表使用thymeleaf循环
        int[] pages = new int[page];
        for (int i = 1; i <= pages.length; i++) {
            pages[i-1] = i;
        }
        return pages;
    }


    /**
     * 通过修改model获取页面内容
     */
    private void getPageInfo(Model model,List<QuestionDTO> questions){
        int count = indexService.selectQuestionCount();
        // 如果用户登录了则展示头像
        String userId = (String)httpSession.getAttribute("userId");
        if (userId != null && !userId.isEmpty()) {
            model.addAttribute("avatar",avatarService.selectUserAvatar(userId));
        }

        model.addAttribute("pages",getPages(count));

        model.addAttribute("questionlist", questions);

        // 未读通知数量
        model.addAttribute("unreadCount",notificationService.countUNREADNotification(userId));

        // 本周用户榜单
        model.addAttribute("leaderBoard",commentService.selectOneWeekUserLeaderBoard());

        // 本周文章榜单(海报),由于前端特殊不能遍历，三张图分别上传
        List<PosterDTO> leaderPosters = commentService.selectOneWeekPoster();
        for (int i = 0; i < 3; i++) {
            if (leaderPosters.size() >= i + 1){
                model.addAttribute("poster"+(i+1),leaderPosters.get(i));
            }else {
                model.addAttribute("poster"+(i+1),null);
            }
        }

    }


}
